package com.slkj.shilixiaoyuanapp.ui.teacher.tool.notice;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.slkj.shilixiaoyuanapp.BuildConfig;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.entity.FileEntity;
import com.slkj.shilixiaoyuanapp.entity.UpFileEntity;
import com.slkj.shilixiaoyuanapp.entity.code.UiCode;
import com.slkj.shilixiaoyuanapp.entity.commitdata.NoticeStudentEntity;
import com.slkj.shilixiaoyuanapp.entity.contacts.ContactsPeopleEntity;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.ChoseObjActivity;
import com.slkj.shilixiaoyuanapp.ui.common.ChoseObjActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.common.adapter.ChosePicAdapter;
import com.slkj.shilixiaoyuanapp.ui.common.adapter.FileAdapter;
import com.slkj.shilixiaoyuanapp.util.StringUtils;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.FileUtils;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.DividerItemDecoration;
import com.slkj.shilixiaoyuanapp.view.NumberEditText;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import io.reactivex.ObservableSource;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;
import ru.bartwell.exfilepicker.ExFilePicker;
import ru.bartwell.exfilepicker.data.ExFilePickerResult;

import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHOSE_SEND_OBJ_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_FILE_CODE;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_MAX_SIZW;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_SPAN_COUNT;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.NO_CHOSE;
import static com.slkj.shilixiaoyuanapp.ui.common.ChoseObjActivity.getCheckConstactsByGroup;

@RuntimePermissions
@ActivityInfo(layout = R.layout.activity_send_notice, title = "发布通知", rightHint = "历史记录")
public class SendNoticeActivity extends BaseActivity {
    @BindView(R.id.tv_obj)
    TextView tvObj;
    @BindView(R.id.edit_title)
    EditText editTitle;
    @BindView(R.id.recyc_pic)
    RecyclerView recycerPic;
    @BindView(R.id.recyc_file)
    RecyclerView recycFile;
    @BindView(R.id.edit_content)
    NumberEditText editContent;
    ArrayList<String> picPaths = new ArrayList<>();
    ArrayList<FileEntity> filePaths = new ArrayList<>();
    FileAdapter fileAdapter;
    ChosePicAdapter adapter;
    public TakePictureUtils takePictureUtils;
    private String ids;
    public static final String tag = "SendNoticeActivity";
    String imgFile = "";
    ArrayList<ContactsPeopleEntity> contactsAll = new ArrayList<>();
    ArrayList<ContactsPeopleEntity> contactsCheck = new ArrayList<>();
    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        recycerPic.setLayoutManager(new GridLayoutManager(this, CHOSE_PIC_SPAN_COUNT));
        recycFile.setLayoutManager(new LinearLayoutManager(this));
        recycFile.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        adapter = new ChosePicAdapter(picPaths, this);
        fileAdapter = new FileAdapter(this, filePaths);
        recycerPic.setAdapter(adapter);
        recycFile.setAdapter(fileAdapter);
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override
            public void successful(File outFile) {
                picPaths.add(outFile.getPath());
                adapter.notifyItemInserted(picPaths.size());
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
            }
        });
    }

    @Override
    protected void onRightTitleClick() {
        startActivity(NoticeHistoryListActivity.class);
    }

    @OnClick(R.id.tv_up)
    void upData() {
        if (TextUtils.isEmpty(ids)) {
            showToast("请选择发布对象");
            return;
        }
        String title = editTitle.getText().toString();
        if (TextUtils.isEmpty(title)) {
            showToast("请输入通知题目");
            return;
        }
        String context = editContent.getText();
        if (TextUtils.isEmpty(context)) {
            showToast("请输入通知内容");
            return;
        }

        UpdataFileUtil.UpImgObservable("notice", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, List<UpFileEntity>>() {
                    @Override
                    public ObservableSource<CommonResult<List<UpFileEntity>>> back(List<String> result) {
                        imgFile = StringUtils.listToString(result);
                        return UpdataFileUtil.UpFileObservable("notice", filePaths);
                    }
                })
                .flatMap(new BaseFunctionCallBack<List<UpFileEntity>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<UpFileEntity> result) {
                        Gson gson = new Gson();
                        String file = gson.toJson(result);
                        List<NoticeStudentEntity> student = new ArrayList<>();
                        ArrayList<ContactsPeopleEntity> teacher = new ArrayList<>();
                        for (ContactsPeopleEntity entity : contactsCheck){
                            if (entity.getParent() == 0){
                                teacher.add(entity);
                            }else {
                                student.add(new NoticeStudentEntity(entity.getId(),entity.getParent()));
                            }
                        }
                        String tIds = gson.toJson(ChoseObjActivity.getIds(teacher));
                        Log.d(TAG, ">>>back- 老师id--" + tIds);
                        Log.d(TAG, ">>>back- 学生id--" + gson.toJson(student));

                        return HttpHeper.get().toolService().addTz(1, title, context, imgFile, file, tIds,gson.toJson(student));
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true, SendNoticeActivity.this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        LoadSuccessAndFailDialog.showSuccess(SendNoticeActivity.this,data);
                        clearContent();
                    }
                });

    }

    /**
     * 选择发布对象
     **/
    @OnClick(R.id.layout_chose_obj)
    void choseObj() {
        ChoseObjActivity__JumpCenter.builder(this)
                .setMaxNum(Integer.MAX_VALUE)
                .setTag(tag).setContacts(contactsAll).create().go();
    }


    @Recipient(tag = tag + CHOSE_SEND_OBJ_FINSH)
    void onPeopleCheck(ArrayList<ContactsPeopleEntity> back) {
        contactsAll.clear();
        contactsAll.addAll(back);
        contactsCheck.clear();
        contactsCheck.addAll(getCheckConstactsByGroup(back));
        ids = ChoseObjActivity.getIds(contactsCheck).toString();
        if (contactsCheck.isEmpty()){
            tvObj.setText("");
        }else {
            tvObj.setText(ChoseObjActivity.getInfos(contactsCheck));
        }


    }

    @OnClick(R.id.layout_chose_pic)
    void chosePic() {
        if (picPaths.size() == CHOSE_PIC_MAX_SIZW) {
            showToast("最多添加" + CHOSE_PIC_MAX_SIZW + "张图片");
            return;
        }
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }

            @Override
            public void chosePhoto() {
                SendNoticeActivityPermissionsDispatcher.onAgreePermissionWithPermissionCheck(SendNoticeActivity.this);
            }
        });

    }

    @OnClick(R.id.layout_chose_file)
    public void onLayoutChoseFileClicked() {
        ExFilePicker exFilePicker = new ExFilePicker();
        exFilePicker.setStartDirectory(Environment.getExternalStorageState());
        exFilePicker.setChoiceType(ExFilePicker.ChoiceType.FILES);
        exFilePicker.start(this, CHOSE_FILE_CODE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == UiCode.CHOSE_PIC_CODE) {
                List<Uri> mSelected = Matisse.obtainResult(data);
                for (int i = 0; i < mSelected.size(); i++) {
                    String filePath = FileUtils.getPathByUri(this, mSelected.get(i));
                    picPaths.add(filePath);
                }
                adapter.notifyItemRangeInserted(picPaths.size(), mSelected.size());
            } else if (requestCode == CHOSE_FILE_CODE) {
                ExFilePickerResult result = ExFilePickerResult.getFromIntent(data);
                if (result != null && result.getCount() > 0) {

                    FileEntity fileEntity = new FileEntity(result);
                    File file = new File(fileEntity.getPath());
                    if (file.length() / 1000000 > 5){
                        showToast("文件最大为5M");
                        return;
                    }
                    filePaths.add(fileEntity);
                    fileAdapter.notifyItemInserted(filePaths.size() );
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SendNoticeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.CAMERA})
    void onAgreePermission() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(CHOSE_PIC_MAX_SIZW - picPaths.size())
                .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID + ".fileprovider"))
                .imageEngine(new GlideEngine())
                .forResult(UiCode.CHOSE_PIC_CODE);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void onDeniedPermission() {
        showToast("读取照片权限获取失败");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);

    }


}
